package com.xca.znb.view;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.xca.znb.R;
import com.xca.znb.entity.Account;
import com.xca.znb.entity.Goods;
import com.xca.znb.entity.User;
import com.xca.znb.model.impl.EndPayImpl;
import com.xca.znb.presenter.EndPayPresenter;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class EndPayActivity extends AppCompatActivity {
    private ImageButton Back ;
    private Button Pay ;
    private TextView payMoney , balanceMoney , recharge ;
    private EndPayPresenter presenter ;
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.end_pay_money);
        Back = findViewById(R.id.pay_back) ;
        Pay = findViewById(R.id.pay_sure_btn) ;
        payMoney = findViewById(R.id.pay_money) ;
        balanceMoney = findViewById(R.id.pay_end_balance_money);
        recharge = findViewById(R.id.pay_to_recharge) ;
        final EditText editText1 = new EditText(this);
        editText1.setHint("输入在此处");

        EndPayImpl endPayImpl = new EndPayImpl(this);
        presenter = new EndPayPresenter(endPayImpl);


        Intent intent = getIntent();
        int localId = intent.getIntExtra("payLocalId" , 1);//地址ID
        int goodsId = intent.getIntExtra("payGoodsId" , 1);//商品ID
        int num = intent.getIntExtra("payNum" , 1);//购买数量
        String remark = intent.getStringExtra("payRemark");//备注
        SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
        String phone = sharedPreferences.getString("phone" , "");//买家电话
        Goods goods = presenter.getGoodsById(goodsId);
        String sales = goods.getPublisher() ;

        //订单状态
        String type = "待发货";
        String buyerAccountType = "购买" ;
        String salesAccountType = "出售";
        //获取当前时间：精确到秒
        LocalDateTime nowTime = LocalDateTime.now();
        String secTime = nowTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String dayTime = nowTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));


        //获取支付密码
        User user = presenter.getUserByPhone(phone);
        String payPassword = user.getPay_password() ;
        //设置支付金额
        payMoney.setText(String.valueOf(goods.getPrice() * num));
        double needPay = goods.getPrice()*num ;
        refreshData();

        Pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //设置余额金额
                double balanceNum = presenter.getBalance(phone);
                if (balanceNum >= needPay){
                    AlertDialog.Builder builder = new AlertDialog.Builder(EndPayActivity.this);
                    builder.setMessage("请输入支付密码") ;
                    final EditText editText = new EditText(EndPayActivity.this);
                    builder.setView(editText);
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String editInput = editText.getText().toString();
                            if (editInput.equals(payPassword)){
                                boolean isAdd =  presenter.addOrder(localId,goodsId,num,remark,phone,sales,type,secTime);
                                if (isAdd){
                                    presenter.insertAccount(phone,needPay,buyerAccountType,dayTime,secTime);
                                    presenter.insertAccount(sales,needPay,salesAccountType,dayTime,secTime);
                                    balanceMoney.setText(String.valueOf(balanceNum - needPay));
                                    Toast.makeText(EndPayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                                    finish();
                                }else {
                                    Toast.makeText(EndPayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                                }

                            }else {
                                Toast.makeText(EndPayActivity.this, "支付密码错误", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                    builder.setNegativeButton("取消" , null) ;
                    builder.create().show();
                }else {
                    Toast.makeText(EndPayActivity.this, "余额不足，请充值", Toast.LENGTH_SHORT).show();
                }
            }
        });

        recharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(EndPayActivity.this , MyAssetsActivity.class) ;
                startActivity(intent1);
            }
        });
        Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    private void refreshData(){
        Intent intent = getIntent();
        int goodsId = intent.getIntExtra("payGoodsId" , 1);//商品ID
        int num = intent.getIntExtra("payNum" , 1);//购买数量
        SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
        String phone = sharedPreferences.getString("phone" , "");//买家电话
        Goods goods = presenter.getGoodsById(goodsId);
        //设置支付金额
        payMoney.setText(String.valueOf(goods.getPrice() * num));
        //设置余额金额
        double balanceNum = presenter.getBalance(phone);
        String balNum = String.valueOf(balanceNum);
        balanceMoney.setText(balNum);
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshData();
    }
}
